package org.netwia.networks.nodes;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.netwia.networks.Node;

/**
 * This is implementation of node which sums all inputs.
 * Expectation is that all values from all maps are double numbers.
 * Result is a map with single key called result and value is sum of all inputs.
 * 
 * @author radek.hecl
 *
 * @param <T> network type parameter
 */
public class DoubleSerializableMapSumNode<T extends Map<String, String> & Serializable> implements Node<T> {

    /**
     * Builder object.
     *
     * @param <T> network type parameter
     */
    public static class Builder<T extends Map<String, String> & Serializable> {

        /**
         * Builds the result object.
         * 
         * @return created object
         */
        public DoubleSerializableMapSumNode<T> build() {
            return new DoubleSerializableMapSumNode<T>(this);
        }
    }

    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public DoubleSerializableMapSumNode(Builder<T> builder) {
        guardInvariants();
    }

    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    private void guardInvariants() {
    }

    @SuppressWarnings("unchecked")
    @Override
    public T process(Map<String, T> inputs) {
        double res = 0;
        for (String inputName : inputs.keySet()) {
            for (String key : inputs.get(inputName).keySet()) {
                res = res + Double.valueOf(inputs.get(inputName).get(key)); 
            }
        }
        HashMap<String, String> resMap = new HashMap<String, String>();
        resMap.put("result", Double.valueOf(res).toString());
        return (T)resMap;
    }
    
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}
